package com.example.tnot.Student;

//import static com.example.tnot.login.fragmentui.LoginFragment.socketClient;
import static com.example.tnot.R.*;
import static com.example.tnot.login.fragmentui.LoginFragment.student_data;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.example.tnot.R;
import com.example.tnot.api.SocketClient;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DebugStudentActivity extends AppCompatActivity {
    private Button sendBtn,goVideo,to_live;
    private TextView msgText;
    private SocketClient socketClient;
    private EditText sendText,room_id;
    private Date date = new Date(System.currentTimeMillis());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
    private  String history;

    boolean checkStringBlank(String s)
    {
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)!=' ')
            {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_student_home);

        sendText = findViewById(R.id.sendText);
        // 初始化视图
        sendBtn = findViewById(R.id.button);
        msgText = findViewById(R.id.text1);
        goVideo = findViewById(R.id.goVideo1);
        to_live = findViewById(R.id.to_live);
        room_id = findViewById(R.id.room_id);
        //socketClient.studentConnect(); // 发送学生连接事
        // 获取Socket单例并连接，保证连接在最前面
         socketClient = SocketClient.getInstance();
        socketClient.connect();
        while(!socketClient.getmSocket())
        {;}
        socketClient.listenConnect();
        //socketClient.teacherConnect(); //Debug 测试教师连接1
        socketClient.studentConnect();

        // 按钮点击事件（学生发送消息示例，实际可能无权限，仅作测试）
        sendBtn.setOnClickListener(v -> {
            String messge = sendText.getText().toString().trim();//删除前面和末尾的空格
            if(!messge.isEmpty() && !checkStringBlank(messge))
            {
                String text = "[";
                text+=simpleDateFormat.format(date);
                try {
                    text+=student_data.getString("username");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                text+="]";
                text += messge;
                text+="\n";
                socketClient.sendBroadcast(text);
                sendText.setText("");
            }
            else
            {
                Toast.makeText(DebugStudentActivity.this, "发送信息不能为空", Toast.LENGTH_SHORT).show();
            }
        });

        // 监听服务器广播消息// type 是消息类型："broadcast" 或 "message"
        socketClient.setOnMessageReceivedListener(message -> {
            // 在UI线程更新文本

            if(history == null)
                history = message;
            else
                history+=message;
            runOnUiThread(() -> msgText.setText(history));
        });

        // 监听错误信息
        socketClient.setOnErrorReceivedListener(errorMessage -> {
            runOnUiThread(() -> {
                // 显示错误信息，例如使用 Toast
                Toast.makeText(DebugStudentActivity.this, "提示: " + errorMessage, Toast.LENGTH_SHORT).show();
            });
        });

        // 视频测试按钮
        goVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it =new Intent(DebugStudentActivity.this,DebugVideoActivity.class);
                startActivity(it);
            }
        });

        //直播测试按钮
        to_live.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent it =new Intent(DebugStudentActivity.this,StudentLiveActivity.class);
                String roomId = room_id.getText().toString(); // 实际应用中可能是从接口或其他地方获取的
                it.putExtra("ROOM_ID", roomId);
                startActivity(it);
            }
        });

    }

    // 生命周期管理：页面销毁时断开连接
    @Override
    protected void onDestroy() {
        super.onDestroy();
        socketClient.disconnect();
        socketClient.setOnErrorReceivedListener(null);
    }


}